package utils

import (
	"crypto"
	"crypto/ecdsa"
	"crypto/rand"
	"crypto/x509"
	"encoding/asn1"
	"encoding/pem"
	"errors"
	"fmt"
	"gitee.com/zxs-micro/zxs-micro-common/log"
	"math/big"
)

type RSStruct struct {
	R, S *big.Int
}

var (
	DEFAULT_HASH = crypto.SHA256
)

func EcdsaSign(origData []byte, privateKeyPem []byte, hash crypto.Hash) (bs []byte, err error) {
	key, err := ParseEcdsaPrivateKey(privateKeyPem)
	if err != nil {
		return nil, err
	}

	h := hash.New()
	h.Write(origData)
	digest := h.Sum(nil)

	bs, err = key.Sign(rand.Reader, digest, nil)

	//r, s, err = ecdsa.Sign(rand.Reader, key, digest)
	if err != nil {
		return nil, fmt.Errorf("ecdsa sign fail: %s", err.Error())
	}

	return
}

func EcdsaVerifySign(signbs []byte, data []byte, pemCert string, hash crypto.Hash) (bool, error) {

	cert, err := ParsePem2Cert(pemCert)
	if err != nil {
		return false, fmt.Errorf("ParseCertificate failed: %s", err.Error())
	}

	h := hash.New()
	h.Write(data)
	digest := h.Sum(nil)

	ecdsaPubKey, _ := cert.PublicKey.(*ecdsa.PublicKey)

	var rs RSStruct
	_, err = asn1.Unmarshal(signbs, &rs)
	if err != nil {
		return false, err
	}

	result := ecdsa.Verify(ecdsaPubKey, digest, rs.R, rs.S)

	return result, nil
}

func ParsePem2Cert(pemCert string) (*x509.Certificate, error) {
	block, _ := pem.Decode([]byte(pemCert))
	if block == nil {
		log.Log.Errorf("failed to decode pem cert")
		return nil, errors.New("failed to decode pem cert")
	}
	cert, err := x509.ParseCertificate(block.Bytes)
	if err != nil {
		log.Log.Errorf("ParseCertificate fail: %s", err.Error())
		return nil, err
	}

	return cert, nil
}

func ParseEcdsaPrivateKey(pemkey []byte) (*ecdsa.PrivateKey, error) {
	block, _ := pem.Decode(pemkey)
	if block == nil {
		return nil, fmt.Errorf("Decode block == nil")
	}
	key, err := x509.ParseECPrivateKey(block.Bytes)
	if err != nil {
		return nil, fmt.Errorf("ParseECPrivateKey fail: %s", err.Error())
	}
	return key, nil
}
